package com.xzs.data.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class ReturnDataDaoJdbcTemplateImpl implements ReturnDataDao {

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    public int add(ReturnData returnData) {
        String sql = "insert into returnData(id,uri,returnData) " +
                "values(:id,:uri,:returnData)";
        Map<String, Object> param = new HashMap<>();
        param.put("id", returnData.getId());
        param.put("returnData", returnData.getReturnData());
        param.put("uri", returnData.getUri());

        return jdbcTemplate.update(sql, param);
    }

    @Override
    public int update(ReturnData returnData) {
        String sql = "update returnData set returnData=:returnData,uri=:uri where id =:id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", returnData.getId());
        param.put("returnData", returnData.getReturnData());
        param.put("uri", returnData.getUri());
        return jdbcTemplate.update(sql, param);
    }

    @Override
    public int delete(String id) {
        String sql = "delete from returnData where id =:id";
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        return jdbcTemplate.update(sql, param);
    }

    @Override
    public String selectByUri(String uri) {
        String sql = "select returnData from returnData  where uri=:uri";
        Map<String, Object> param = new HashMap<>();
        param.put("uri", uri);
        String returnData = "";
        try {

            List<ReturnData> userList = jdbcTemplate.query(sql, param, new BeanPropertyRowMapper<ReturnData>(ReturnData.class));
            if (null != userList && userList.size() > 0) {
                ReturnData user = userList.get(0);
                returnData = user.getReturnData();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnData;
    }

    @Override
    public List<ReturnData> selectAll() {
        String sql = "select * from returnData";
        try {
            List<ReturnData> userList = jdbcTemplate.query(sql, new HashMap<>(), new BeanPropertyRowMapper<ReturnData>(ReturnData.class));

            return userList;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
}
